<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\GoodsType;
use App\Models\GoodsBrand;
use App\Models\Supplier;
use App\Models\GoodsNorm;
use App\Models\Goods;
use App\Http\Controllers\App\BaseController;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller
{
    /**
     * 添加商品前获取参数
     *
     * @return void
     */
    public function showParam()
    {   
        // 商品分类信息
        $type_where[] = [ 'status', '=', '1' ];
        $type_data    = GoodsType::with(['sub_type' => function ( $query ) {
          $query->select('id', 'name', 'pid');
        }])->select('id','name','pid')->where('pid', 0)->get();
      
        // 商品品牌信息
        $brand_where[] = [ 'status', '=', '1' ];
        $brand_data    = GoodsBrand::where($brand_where)->select('name', 'id')->orderBy('sort')->get();

        // 商品供货商信息
        $supplier_where[] = [ 'status', '=', '1' ];
        $supplier_data    = Supplier::where($supplier_where)->select('name', 'id')->get();

        //计价方式信息
        $valuation = config('setup.valuation');

        //零售商信息
        $retail_unit = config('setup.retail_unit');

        $data = [
            'type'        => $type_data,
            'brand'       => $brand_data,
            'supplier'    => $supplier_data,
            'valuation'   => $valuation,
            'retail_nuit' => $retail_unit,
        ];

        return self::json($data);
    }

    /**
     * 添加商品
     *
     * @param Request $request
     * @return void
     */
    public function create( Request $request )
    {
       $name              = $request->input('name');
       $code              = $request->input('code');
       $production_origin = $request->input('production_origin')?:'';
       $manufacturer      = $request->input('manufacturer')?:'';
       $valuation_id      = $request->input('valuation_id');
       $retail_unit_id    = $request->input('retail_unit_id');
       $goods_type_id     = $request->input('goods_type_id');
       $goods_brand_id    = $request->input('goods_brand_id');
       $supplier_id       = $request->input('supplier_id');
       $buying_price      = $request->input('buying_price');
       $trade_price       = $request->input('trade_price')?:0;
       $retail_price      = $request->input('retail_price');
       $market_price      = $request->input('market_price');
       $num               = (int)$request->input('num');
       $is_rebate         = $request->input('is_rebate');

       $admin_id          = session('admin_id', 0);

       $profit            = round( ($retail_price - $buying_price) / $retail_price * 100 );//计算利润率
      
       $norms  = json_decode($request->input('norm'), true);
        
       if ( !$norms ) {
          return self::error('请添加规格');
       }
       $info = Goods::create([
           'name'              => $name,
           'code'              => $code,
           'production_origin' => $production_origin,
           'manufacturer'      => $manufacturer,
           'valuation_id'      => $valuation_id,
           'retail_unit_id'    => $retail_unit_id,
           'goods_type_id'     => $goods_type_id,
           'goods_brand_id'    => $goods_brand_id,
           'supplier_id'       => $supplier_id,
           'buying_price'      => $buying_price,
           'trade_price'       => $trade_price,
           'retail_price'      => $retail_price,
           'market_price'      => $market_price,
           'num'               => $num,
           'profit'            => $profit,
           'is_rebate'         => $is_rebate,
           'content'           => '',
           'admin_id'          => $admin_id,
       ]);
       
       foreach ($norms as $k => $v) {

           $data[] = new GoodsNorm([
                    'name' => $v['name'],
                    'buying_price' =>  $buying_price,
                    'trade_price'  =>  $trade_price,
                    'retail_price' =>  $retail_price,  
                    'profit'       =>  $profit,   
                    'admin_id'     =>  $admin_id,      
                ]);
       }

       $info->norm()->saveMany($data);
       
       return self::success('添加成功');
    }

    /**
     * 修改商品
     *
     * @return void
     */
    public function edit( Request $request )
    {
        $name              = $request->input('name');
        $code              = $request->input('code');
        $production_origin = $request->input('production_origin')?:'';
        $manufacturer      = $request->input('manufacturer')?:'';
        $valuation_id      = $request->input('valuation_id');
        $retail_unit_id    = $request->input('retail_unit_id');
        $goods_type_id     = $request->input('goods_type_id');
        $goods_brand_id    = $request->input('goods_brand_id');
        $supplier_id       = $request->input('supplier_id');
        $buying_price      = $request->input('buying_price');
        $trade_price       = $request->input('trade_price')?:0;
        $retail_price      = $request->input('retail_price');
        $market_price      = $request->input('market_price');
        $num               = (int)$request->input('num');
        $is_rebate         = $request->input('is_rebate');
        $is_sell           = $request->input('is_sell');
        $id                = $request->input('id');
        $status            = $request->input('status');

        $admin_id          = session('admin_id', 0);

        $profit            = round( ($retail_price - $buying_price) / $retail_price * 100 );//计算利润率
      
        $norms  = json_decode($request->input('norm'), true);
        
        if ( empty( $norms ) ) {
            return self::error('必须填写规格');
        }

        $info = Goods::find($id);
        
        if ( !$info ) {
            return self::error('请传递正确的商品');
        }

        $info->name              = $name;
        $info->code              = $code;
        $info->production_origin = $production_origin;
        $info->manufacturer      = $manufacturer;
        $info->valuation_id      = $valuation_id;
        $info->retail_unit_id    = $retail_unit_id;
        $info->goods_type_id     = $goods_type_id;
        $info->goods_brand_id    = $goods_brand_id;
        $info->supplier_id       = $supplier_id;
        $info->buying_price      = $buying_price;
        $info->trade_price       = $trade_price;
        $info->retail_price      = $retail_price;
        $info->market_price      = $market_price;
        $info->num               = $num;
        $info->profit            = $profit;
        $info->is_rebate         = $is_rebate;
        $info->is_sell           = $is_sell;
        $info->status            = $status;
        $info->admin_id          = $admin_id;
    
        $info->save();

        foreach ($norms as $k => $v) {

            $data[] = new GoodsNorm([
                        'name' => $v['name'],
                        'buying_price' =>  $buying_price,
                        'trade_price'  =>  $trade_price,
                        'retail_price' =>  $retail_price,  
                        'profit'       =>  $profit,   
                        'admin_id'     =>  $admin_id,      
                    ]);
        }
        GoodsNorm::where('goods_id', $id)->delete();

        $info->norm()->saveMany($data);
        
        return self::success('修改成功');
    
    }

    /**
     * 查询商品
     *
     * @param Request $request
     * @return void
     */
    public function show( Request $request )
    {
        $name    = $request->input('name');
        $code    = $request->input('code');
        $type_id = $request->input('type_id');
        $num     = $request->input('num')?:20;
        $status  = $request->input('status', null);
        $is_sell = $request->input('is_sell', null);
        $is_edit = $request->input('is_edit', null);

        $query = Goods::with([
          'norm' => function ( $query ) {
                $query->select('name', 'goods_id');
            },
          'brand' => function ( $query) {
                $query->select('name','id');
          },
          'supplier' => function ( $query ) {
                $query->select('name', 'id');
          }
            ]);
        
        if ( $name ) {
            $where[] = [ 'name', 'like', '%'.$name.'%'];
            $query->where('name', 'like', '%' . $name . '%');
        }

        if ( $is_edit !== null ) {
          $query->where('is_edit', $is_edit);
        }

        if ( $code ) {
            $query->where('code', $code);
        }

        if ( $status !== null) {
          $query->where('status', $status );
        }

        if ( $is_sell !== null) {

          $query->where('is_sell', $is_sell );

        }

        if ( $type_id ) {

            $info = GoodsType::find($type_id);

            $type_ids = ($info['pid'] == 0) ? GoodsType::where('pid', $type_id)->pluck('id') : [$type_id];

            $query->whereIn('goods_type_id', $type_ids);
        }
       
        $numquery =  clone $query;

        $good_num = $numquery->select(DB::raw('count(id) as num'), 'is_sell')->groupBy('is_sell')->get()->toArray();  
        
        //$data = $query->orderBy('sort')->orderBy('id', 'desc')->paginate($num);
        $data = $query->orderBy(DB::raw('case when sort<>0 then sort else 9999999999 end'))->orderBy('id', 'desc')->paginate($num);
        return self::json(['good' => $data, 'num' => $good_num]);
    }

    /**
     * 商品上下架
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function shelves( Request $request)
    {
      $is_sell  = (int)$request->input('sell');
      $good_ids = $request->input('ids');
      $admin_id = session('admin_id');

      if ( !in_array($is_sell, [0, 1], true)) {
        return self::error('上下架参数错误');
      }
    
      $good_ids = explode(',', $good_ids);
      
      $aa = Goods::whereIn('id', $good_ids)->update([
            'is_sell'    => $is_sell,
            'updated_at' => date('Y-m-d H:i:s', time()),
            'admin_id'   => $admin_id
        ]);
      
      return self::success('成功');
    }

    /**
     * 商品编辑
     * @return [type] [description]
     */
    public function editGood( Request $request )
    {
      $id      = $request->input('id');
      $pic     = $request->input('pic');
      $content = (string)$request->input('content');
      $note    = (string)$request->input('note', '');
      $status  = $request->input('status', 0);

      $info = Goods::find($id);
   
      $info->pic     = $pic;
      $info->content = $content;
      $info->note    = $note;
      $info->status  = $status;
      $info->save();

      return self::success('编辑成功');

    }

    /**
     * 商品详情
     * @return [type] [description]
     */
    public function detail( Request $request)
    {
      $id = $request->input('id');

      $info = Goods::with([
                'norm' => function ( $query ) {
                          $query->select('name', 'goods_id');
                      },
                 'brand' => function ( $query) {
                          $query->select('name','id');
                },
                'supplier' => function ( $query ) {
                          $query->select('name', 'id');
                }

              ])->where('id', $id)->first();
      return self::json($info);
    }

    /**
     * 验证国际条形码是否存在
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function checkCode( Request $request)
    {
      $code = $request->input('code');

      $value = Goods::where('code', $code)->first();

      if ( $value ) {

        return self::error('条形码已存在', 10);

      } else {

        return self::success('可以添加');

      }
    }

    /**
     * 排序
     * @return [type] [description]
     */
    public function sort( Request $request )
    {
      $name = $request->input('name');
      $num  = $request->input('num');
      $id   = $request->input('id');

      $info = Goods::find($id);

      if ( !$info) {
        return self::error('暂无该商品');
      }

      $info->$name = $num;
      $info->save();

      return self::success('修改成功');

    }
}
